package hui.zhang.bos.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import hui.zhang.bos.utils.BaseAction;
import hui.zhang.constant.Constants;
import hui.zhang.domain.page.PageBean;
import hui.zhang.domain.take_delivery.Promotion;

@Controller
@ParentPackage("struts-default")
@Namespace("/")
@Scope("prototype")
@SuppressWarnings("all")
public class PromotionAction extends BaseAction<Promotion> {
	
	@Action(value="promotion_pageQuery")
	public String pageQuery() {
		//基于webservice获取bos_management的活动列表数据信息
		PageBean<Promotion> pageBean = 
				WebClient.create(Constants.BOS_MANAGEMENT_URL+"/bos_management/services/promotionService/pageQuery?page="
				+page+"&rows="+rows).accept(MediaType.APPLICATION_JSON).get(PageBean.class);
		
		toJsonAndResponse(pageBean);
		return NONE;
	}
	
	@Action(value="promotion_showDetail")
	public String showDetail() throws IOException, TemplateException {
		// 先判断id是否存在，存在直接返回
		String realPath = ServletActionContext.getServletContext()
				.getRealPath("/freemarker");
		File htmlFile = new File(realPath+"/"+model.getId()+".html");
		//如果html文件不存在，通过模板生成
		if(!htmlFile.exists()) {
			Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
			configuration.setDirectoryForTemplateLoading(new File(
					ServletActionContext.getServletContext()
					.getRealPath("/WEB-INF/freemarker_templates")));
			//获取模板对象
			Template template = configuration.getTemplate("promotion_detail.ftl");
			//动态数据
			Promotion promotion = 
					WebClient.create(Constants.BOS_MANAGEMENT_URL+"/bos_management/services/promotionService/promotion/"+model.getId())
					.accept(MediaType.APPLICATION_JSON).get(Promotion.class);
			Map<String, Object> parameterMap = new HashMap<String, Object>();
			parameterMap.put("promotion", promotion);
			//合并输出
			template.process(parameterMap, new OutputStreamWriter
					(new FileOutputStream(htmlFile),"utf-8"));
		}
		
		// 存在，返回
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		FileUtils.copyFile(htmlFile, ServletActionContext
				.getResponse().getOutputStream());
		return NONE;
	}

}
